/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.portalcenter.api;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hallele.infrastructure.metadata.constant.TokenConst;
import cn.hallele.infrastructure.metadata.io.R;
import cn.hallele.infrastructure.metadata.io.Response;
import cn.hallele.mc.sdk.portalcenter.api.AuthApi;
import cn.hallele.mc.sdk.portalcenter.common.constants.ReqPathConst;
import cn.hallele.mc.sdk.portalcenter.dto.CaptchaDTO;
import cn.hallele.mc.sdk.portalcenter.dto.LoginResDTO;
import cn.hallele.ms.infrastructure.auditlog.annotation.ApiLog;
import cn.hallele.ms.portalcenter.das.AuthDBDas;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * hallele_ms_portalcenter
 *
 * @author anle5
 * @since 2024/10/11 21:54
 */
@RestController
@RequestMapping(ReqPathConst.AUTH_V1)
public class AuthController implements AuthApi {
    @Autowired
    private AuthDBDas authDBDas;

    /**
     * 生成验证码
     *
     * @return 验证码
     */
    @Override
    @ApiLog(id = "AUTH_V1_CREATE_CAPTCHA")
    public Response<CaptchaDTO> createCaptcha() {
        CaptchaDTO captcha = authDBDas.createCaptcha();
        return R.ok(captcha);
    }

    /**
     * 登录接口
     *
     * @param username    用户名
     * @param password    密码
     * @param captchaKey  验证码key
     * @param captchaCode 验证码值
     * @return LoginResDTO
     */
    @Override
    @ApiLog(id = "AUTH_V1_LOGIN")
    public Response<LoginResDTO> login(@RequestParam("username") String username,
                                       @RequestParam("password") String password,
                                       @RequestParam("captchaKey") String captchaKey,
                                       @RequestParam("captchaCode") String captchaCode) {
        authDBDas.login(username, password, captchaKey, captchaCode);
        return R.ok(LoginResDTO.builder()
                .tokenType(TokenConst.TYPE_BEARER)
                .token(StpUtil.getTokenInfo().getTokenValue())
                .build());
    }

    /**
     * 注销登录
     *
     * @return 空
     */
    @Override
    @SaCheckLogin
    @ApiLog(id = "AUTH_V1_LOGOUT")
    public Response<Void> logout() {
        authDBDas.logout();
        return R.ok(null);
    }
}
